<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" inline v-show="showSearch" label-width="68px">
      <el-form-item label="试卷类型" prop="paperType">
        <el-select v-model="queryParams.paperType" placeholder="请选择试卷类型" clearable>
          <el-option
            v-for="dict in dict.type.slpaper_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试卷标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入试卷标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:slpaper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:slpaper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:slpaper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:slpaper:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="slpaperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="试卷类型" align="center" prop="paperType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.slpaper_type" :value="scope.row.paperType"/>
        </template>
      </el-table-column>
      <el-table-column label="试卷标题" align="center" prop="name" />
      <el-table-column label="试卷年份" align="center" prop="paperYear" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:slpaper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:slpaper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改申论试卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 材料 -->
        <div v-for="(material, index) in form.materials" :key="index">
          <el-form-item :label="'资料' + getChineseNumber(index + 1)">
            <editor v-model="form.materials[index]" :min-height="192" />
            <el-button size="mini" type="danger" @click="removeMaterial(index)">删除当前'给定资料'</el-button>
          </el-form-item>
        </div>
        <el-button size="mini" type="primary" @click="addMaterial">添加'给定资料'</el-button>
        <el-divider></el-divider>

        <!-- 题干 -->
        <div v-for="(content, index) in form.content" :key="index">
          <el-form-item :label="getChineseNumber(index + 1)">
            <editor v-model="form.content[index]" :min-height="192" />
            <el-button size="mini" type="danger" @click="removeContent(index)">删除当前'作答要求'</el-button>
          </el-form-item>
        </div>
        <el-button size="mini" type="primary" @click="addContent">添加'作答要求'</el-button>
        <el-divider></el-divider>

        <!-- 参考答案 -->
        <div v-for="(answer, index) in form.suggestedAnswer" :key="index">
          <el-form-item :label="'参考答案' + getChineseNumber(index + 1)">
            <editor v-model="form.suggestedAnswer[index]" :min-height="192" />
            <el-button size="mini" type="danger" @click="removeAnswer(index)">删除当前参考答案</el-button>
          </el-form-item>
        </div>
        <el-button size="mini" type="primary" @click="addAnswer">添加答案</el-button>

        <el-form-item label="试卷标题" prop="name">
          <el-input v-model="form.name" type="textarea" placeholder="请输入试卷标题" />
        </el-form-item>
        <el-form-item label="试卷类型" prop="paperType">
          <el-select v-model="form.paperType" placeholder="请选择试卷类型">
            <el-option
              v-for="dict in dict.type.slpaper_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷年份" prop="paperYear">
          <el-input v-model="form.paperYear" placeholder="请输入试卷年份" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlpaper, getSlpaper, delSlpaper, addSlpaper, updateSlpaper } from "@/api/business/slpaper";
import { allCorrects, delCorrect } from "@/api/business/correct";

export default {
  name: "Slpaper",
  dicts: ['slpaper_type'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      slpaperList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materials: null,
        content: null,
        suggestedAnswer: null,
        name: null,
        paperType: null,
        paperYear: null
      },
      form: {
        id: null,
        materials: [],
        content: [],
        suggestedAnswer: [],
        name: null,
        paperType: null,
        paperYear: null
      },
      rules: {
        name: [
          { required: true, message: "试卷标题不能为空", trigger: "blur" }
        ],
        paperType: [
          { required: true, message: "试卷类型不能为空", trigger: "change" }
        ],
        paperYear: [
          { required: true, message: "试卷年份不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    addMaterial() {
      this.form.materials.push(""); // 添加一个新的空材料
    },
    removeMaterial(index) {
      this.form.materials.splice(index, 1); // 删除指定索引的材料
    },
    addContent() {
      this.form.content.push(""); // 添加一个新的空题干
    },
    removeContent(index) {
      this.form.content.splice(index, 1); // 删除指定索引的题干
    },
    addAnswer() {
      this.form.suggestedAnswer.push(""); // 添加一个新的空参考答案
    },
    removeAnswer(index) {
      this.form.suggestedAnswer.splice(index, 1); // 删除指定索引的参考答案
    },
    getList() {
      this.loading = true;
      listSlpaper(this.queryParams).then(response => {
        this.slpaperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        materials: [],
        content: [],
        suggestedAnswer: [],
        name: null,
        paperType: null,
        paperYear: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加申论试卷管理";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSlpaper(id).then(response => {
        this.form = response.data;
        this.form.materials = JSON.parse(response.data.materials);
        this.form.content = JSON.parse(response.data.content);
        this.form.suggestedAnswer = JSON.parse(response.data.suggestedAnswer);
        this.open = true;
        this.title = "修改申论试卷管理";
      });
    },
    submitForm() {
  // 将数组转换为 JSON 字符串
  const materials = JSON.stringify(this.form.materials);
  const content = JSON.stringify(this.form.content);
  const suggestedAnswer = JSON.stringify(this.form.suggestedAnswer);

  // 验证表单
  this.$refs["form"].validate(valid => {
    if (valid) {
      // 使用 nextTick 确保 DOM 更新后执行
      this.$nextTick(() => {
        if (this.form.id != null) {
          updateSlpaper({ ...this.form, materials, content, suggestedAnswer }).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          addSlpaper({ ...this.form, materials, content, suggestedAnswer }).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    }
  });
},
handleDelete(row) {
    const ids = row.id || this.ids;
    this.$modal.confirm('删除操作是不可逆的，是否确认删除？').then(() => {
        // 查询与 slquestion 相关的 correct
        return allCorrects({ paperId: ids }); // 假设这里的参数为 questionId
    }).then(response => {
        // 打印返回的 correct 数据
        const correctIds = response.data.map(item => item.id);
        console.log('准备删除的 correct ID:', correctIds);

        // 删除所有相关的 correct
        const deletePromises = correctIds.map(id => {
            return delCorrect(id); // 假设 delCorrect 是删除 correct 的 API
        });

        return Promise.all(deletePromises);
    }).then(() => {
        // 删除 slpaper
        return delSlpaper(ids);
    }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
    }).catch(error => {
        console.error('删除过程中发生错误:', error);
    });
},
    handleExport() {
      this.download('business/slpaper/export', {
        ...this.queryParams
      }, `slpaper_${new Date().getTime()}.xlsx`);
    },
    getChineseNumber(num) {
      const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return chineseNumbers[num] || '';
    }
  }
};
</script>
